import router from './index'
//@ts-ignore
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import useUserStore from '../store/modules/user'
import store from '../store'
let userStore = useUserStore(store)
// nprogress.configrue({showSpinner:false})

export class Permission {
  constructor() {
    router.beforeEach(async (to, from, next) => {
      if (userStore.token) {
        console.log('出发')
        console.log(to)
        console.log(from)

        //登录状态
        if (userStore.username) {
          if (to.path == '/login' && from.path != '/login') {
            console.log('执行')
            next('/home')
          } else {
            //没有过期
            next()
          }
        } else {
          try {
            await userStore.requestUserInfo()
            next({ ...to })
          } catch (e) {
            await userStore.exitLogin()
            next('/login?redirect=' + to.path)
          }
        }
      } else {
        console.log('未登录状态')

        //未登录状态
        if (to.path == '/login') {
          next()
        } else {
          next({ path: '/login', query: { redirect: to.path } })
        }
      }
      nprogress.start()
      next()
    })

    router.afterEach(() => {
      nprogress.done()
    })
  }
}
